<?php
/**
 * Created by PhpStorm.
 * Author: 芸签cms www.yunqiancms.com
 * User: sun
 * Date: 2022/6/27
 * Time: 4:10 PM
 */
namespace app\common\models;

use app\common\exceptions\BizException;
use app\common\helpers\Cache;
use app\common\traits\ValidatorTrait;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Notifications\Notifiable;

class AdminUser extends Authenticatable
{
    use Notifiable;
    use ValidatorTrait;
    use ValidatesRequests;

    public $primaryKey = 'uid';
    public $table = 'yq_admin_user';
    public $timestamps = true;
    protected $guarded = [''];

    //类型(0:超级管理员(admin); 1:普通用户;)
    const TYPE_ADMIN = 0;
    const TYPE_USER = 1;
    //1:审核; 2:有效; 3:禁用
    const STATUS_REVIEW = 1;
    const STATUS_NORMAL = 2;
    const STATUS_BAN = 3;
    public static $status_map = [
        self::STATUS_REVIEW=>'审核中',
        self::STATUS_NORMAL=>'正常',
        self::STATUS_BAN=>'禁用',
    ];


    public function userProfile()
    {
        return $this->hasOne(UserProfile::class, 'uid', 'uid');
    }
    public function userRole()
    {
        return $this->hasOne(UserRole::class, 'user_id', 'uid');
    }
    public function permissions()
    {
        return $this->hasMany(Permission::class, 'item_id', 'uid')
            ->where('type', '=', Permission::TYPE_USER);
    }
    /**
     * 获取并组合用户权限
     * @param $uid
     * @return array
     */
    public static function userPermissionCache()
    {
        $uid = \YunCms::$adminUid;
        if (!isset(static::$userPermission[$uid])) {
            $cacheKey = 'permissions.' . $uid;
            if (!Cache::has($cacheKey)) {
                $userPermission = self::userPermission();

                Cache::put($cacheKey, $userPermission, 4200);
            } else {
                $userPermission = Cache::get($cacheKey);
            }
            static::$userPermission[$uid] = $userPermission;
        }

        return static::$userPermission[$uid];
    }
    /**
     * 获取用户数据库中的所有权限
     * @param $uid
     * @return array
     */
    public static function userPermission()
    {
        set_time_limit(0);
        $uid = \YunCms::$adminUid;
        $userPermissionsModel = self::userPermissionByUid($uid);
        if (!isset($userPermissionsModel)) {
            return [];
        }
        $permissions = [];
        if (!$userPermissionsModel->permissions->isEmpty()) {
            foreach ($userPermissionsModel->permissions as $permission) {
                $permissions[] = $permission->permission;
            }
        }
        if ($userPermissionsModel->userRole && !$userPermissionsModel->userRole->permissions->isEmpty()) {
            foreach ($userPermissionsModel->userRole->permissions as $permission) {
                !in_array($permission->permission, $permissions) && $permissions[] = $permission->permission;
            }
        }
        return $permissions;
    }
    public static function userPermissionByUid($uid){
        $model = static::with([
            'userRole' => function ($query) {
                return $query->with('permissions');
            },
            'permissions'
        ])->where('uid', $uid)->first();
        return $model;
    }
    /**
     * 获取当前时间
     *
     * @return int
     */
    public function freshTimestamp()
    {
        return time();
    }

    /**
     * 避免转换时间戳为时间字符串
     *
     * @param \DateTime|int $value
     * @return \DateTime|int
     */
    public function fromDateTime($value)
    {
        return $value;
    }
    /**
     * 校验参数
     * @param $request
     * @param array $rules
     * @param array $messages
     * @param array $customAttributes
     * @throws BizException
     */
    public function validate($request, array $rules, array $messages = [], array $customAttributes = [])
    {
        $validator = $this->getValidationFactory()->make($request, $rules, $messages, $customAttributes);
        //$validator->errors();

        if ($validator->fails()) {
            throw new BizException($validator->errors()->first());
        }
    }
    public  function atributeNames() {
        return [
            'username'  => '用户名',
        ];
    }

    public  function rules()
    {
        return [
            'username' => 'required'
        ];
    }
}